/* 
 * The MIT License
 *
 * Copyright 2014 Venkat Ram Akkineni.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package org.netbeans.modules.tfsnb.core;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.prefs.Preferences;


/**
 *
 * @author Venkat Ram Akkineni
 */
public class TFSConnectionRegistry {
        
    private static final String MODULE_PREFS_REPO_PREFIX = "TFS";
    private static final Object REPOSITORIES_LOCK = new Object();
    private static final String CONNECTIONS_REPO_PREFIX = MODULE_PREFS_REPO_PREFIX + ".ConnectionSettings";
    public static final String KEY_VALUE_DELIMITER = "<=@=>";
    public static final String CONNECTION_SETTINGS_DELIMITER = "<=^=>";
    private static final ConcurrentHashMap<String, ConnectionSettings> CONNECTIONS_SETTINGS_MAP = new ConcurrentHashMap<>();
    
    private List listeners = Collections.synchronizedList(new LinkedList());
    
    private static TFSConnectionRegistry instance;

    private TFSConnectionRegistry() {}
    
    public static TFSConnectionRegistry getInstance() {
        if(instance == null) {
            instance = new TFSConnectionRegistry();
            instance.retrieveConnections();
        }
        return instance;
    }
    
    public boolean addConnection(final ConnectionSettings conn) {
        if(conn.validate()) {
            CONNECTIONS_SETTINGS_MAP.put(conn.getId(), conn);
            storeConnections();
            return true;
        } else return false;
    }
    
    public ConnectionSettings removeConnection(final String id) {
        ConnectionSettings removedConn = CONNECTIONS_SETTINGS_MAP.remove(id);
        storeConnections();
        return removedConn;
    }
    
    public ConnectionSettings removeConnection(final ConnectionSettings conn) {
        ConnectionSettings removedConn = removeConnection(conn.getId());
        storeConnections();
        return removedConn;
    }
    
    public ConnectionSettings updateConnection(final ConnectionSettings conn) {
        ConnectionSettings removedConn = CONNECTIONS_SETTINGS_MAP.put(conn.getId(), conn);
        storeConnections();
        return conn;
    }
    
    public ConcurrentHashMap<String, ConnectionSettings> retrieveConnections() {
        synchronized(REPOSITORIES_LOCK) {
            Preferences prefs = TFSModuleConfig.getPreferences();
            String conns = prefs.get(CONNECTIONS_REPO_PREFIX, "");
            if(!conns.equals("")) {
                String[] connectionSettings = conns.split(CONNECTION_SETTINGS_DELIMITER);
                CONNECTIONS_SETTINGS_MAP.clear();
                for(String conn: connectionSettings){
                    String[] keyValue = conn.split(KEY_VALUE_DELIMITER);
                    ConnectionSettings connectionSetting = new ConnectionSettings(keyValue[1], keyValue[0]);
                    CONNECTIONS_SETTINGS_MAP.put(keyValue[0], connectionSetting);
                }
            }
            return CONNECTIONS_SETTINGS_MAP;
        }
        
    }   
    
    private boolean storeConnections() {
        synchronized(REPOSITORIES_LOCK) {
            Preferences prefs = TFSModuleConfig.getPreferences();
            StringBuilder prefsString = new StringBuilder();
            Set<String> keySet = CONNECTIONS_SETTINGS_MAP.keySet();
            int index = 0;
            ConcurrentHashMap<String, ConnectionSettings> oldCS = new ConcurrentHashMap(CONNECTIONS_SETTINGS_MAP);
            for(String key: keySet) {
                ConnectionSettings connectionSettings = CONNECTIONS_SETTINGS_MAP.get(key);
                if(index != 0) {
                    prefsString.append(CONNECTION_SETTINGS_DELIMITER);
                }
                prefsString.append(key);
                prefsString.append(KEY_VALUE_DELIMITER);
                prefsString.append(connectionSettings.toString());
                index++;
            }
            prefs.put(CONNECTIONS_REPO_PREFIX, prefsString.toString());
            fire("CONNECTIONS_SETTINGS_MAP", oldCS, CONNECTIONS_SETTINGS_MAP);
            return true;
        }
    }    
    
    public void addPropertyChangeListener(PropertyChangeListener pcl) {
        listeners.add(pcl);
    }
    
    public void removePropertyChangeListener(PropertyChangeListener pcl) {
        listeners.remove(pcl);
    }
    
    private void fire(String propertyName, Object old, Object nu) {
        //Passing 0 below on purpose, so you only synchronize for one atomic call:
        PropertyChangeListener[] pcls = (PropertyChangeListener[]) listeners.toArray(new PropertyChangeListener[0]);
        for (int i = 0; i < pcls.length; i++) {
            pcls[i].propertyChange(new PropertyChangeEvent (this, propertyName, old, nu));
        }
    }
    
}
